package toy.keli.edic

import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResult
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import dagger.hilt.android.AndroidEntryPoint
import toy.keli.edic.ui.MTheme
import toy.keli.edic.ui.Main
import toy.keli.edic.ui.level.LevelViewModel
import toy.keli.edic.util.ActivityRun

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    private val levelModel: LevelViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ActivityRun.setConText(this)
        enableEdgeToEdge()
//        levelModel.getAllLevel()

        setContent {
            MTheme{
                Main()
            }
        }
    }
    protected override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode,resultCode,data)
        ActivityRun.event.onActivityResult(ActivityResult(resultCode,data))
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        val data = Intent()
        data.putExtra("permissions",permissions)
        data.putExtra("grantResults",grantResults)
        ActivityRun.event.onActivityResult(ActivityResult(requestCode,data))
    }
    override fun onDestroy() {
//        val sharedPreferences = this.getSharedPreferences(THEME, Context.MODE_PRIVATE)
//        val editor = sharedPreferences.edit()
//        editor.putInt(LEVEL, viewModel.selectLevel.value)
//        editor.apply()
        super.onDestroy()
    }

    fun onOrientationChange(v: View) {
        val b = v as Button
        val orientation = when (b.text.toString()) {
            "横屏" ->  Configuration.ORIENTATION_LANDSCAPE
            "竖屏" ->  Configuration.ORIENTATION_PORTRAIT
            "方屏" ->  Configuration.ORIENTATION_UNDEFINED
            else -> Configuration.ORIENTATION_LANDSCAPE
        }
        ActivityRun.setOrientationChange(orientation)
    }

    override fun onBackPressed(){
        if(ActivityRun.onBackPressed()) {
            super.onBackPressed()
        }
    }

    override fun onResume() {
        super.onResume()
    }
    //获取导航栏的高度
    private val Context?.navigationBarHeight: Int
        get() {
            this ?: return 0
            val resourceId: Int = resources.getIdentifier("navigation_bar_height", "dimen", "android")
            var height = 0
            if (resourceId > 0) {
                height = resources.getDimensionPixelSize(resourceId)
            }
            return height
        }

}
